import 'package:dio/dio.dart';

//import '../../common/util/log_util.dart';

class RequestException implements Exception {

  static const int CODE_UNKOWN_ERROR = 101;
  static const int CODE_NEWWORK_ERROR = 102;

  final String? message;
  final int? code;

  RequestException([
    this.code,
    this.message,
  ]);

  @override
  String toString() {
    return "$code$message";
  }

  factory RequestException.create(dynamic error) {
    if (error is DioException) {
      switch (error.type) {
        case DioExceptionType.cancel:
          {
            return RequestException(-1, "请求取消");
          }
        case DioExceptionType.connectionError:
          {
            return RequestException(CODE_NEWWORK_ERROR, "连接超时");
          }
        case DioExceptionType.sendTimeout:
          {
            return RequestException(CODE_NEWWORK_ERROR, "请求超时");
          }
        case DioExceptionType.receiveTimeout:
          {
            return RequestException(CODE_NEWWORK_ERROR, "响应超时");
          }
        case DioExceptionType.badResponse:
          {
            try {
              int? errCode = error.response?.statusCode;
              Map<String, dynamic> errMsg = error.response?.data;
              return RequestException(errCode, errMsg["message"]);
            } on Exception catch (_) {
              return RequestException(CODE_UNKOWN_ERROR, "未知错误");
            }
          }

        default:
          {
            return RequestException(CODE_NEWWORK_ERROR, "网络连接异常");
          }
      }
    } else {
      return RequestException(CODE_UNKOWN_ERROR, "未知错误");
    }
  }
}
